package list.simple;

public class MyLinkedList {

    class Node {
        int val;
        Node next;
        Node(int val) {
            this.val = val;
        }
    }
    Node head;
    int size;

    public MyLinkedList() {
        size = 0;
    }

    public int get(int index) {
        if (index < 0 || index >= size || head == null) {
            return -1;
        }

        Node temp = this.head;
        for (int i = 0; i < index && temp != null; i++) {
            temp = temp.next;
        }
        return temp.val;
    }

    public void addAtHead(int val) {
        Node n = new Node(val);
        n.next = this.head;
        this.head = n;
        size++;
    }

    public void addAtTail(int val) {

        Node n = new Node(val);
        if (this.head == null) {
            this.head = n;
            size++;
            return;
        }
        Node temp = this.head;
        while (temp.next != null) {
            temp = temp.next;
        }
        temp.next = n;
        size++;
    }

    public void addAtIndex(int index, int val) {

        if (index > this.size) {
            return;
        }
        if (this.head == null) {
            addAtHead(val);
            return;
        }
        if(index == 0) {
            addAtHead(val);
            return;
        }
        Node temp = this.head;
        for (int i = 0; i < index - 1; i++) {
            temp = temp.next;
        }
        Node next = temp.next;
        temp.next = new Node(val);
        temp.next.next = next;
        size++;
    }

    public void deleteAtIndex(int index) {

        if (index == 0) {
            this.head = this.head.next;
            size--;
            return;
        }
        if (size <= index) {
            return;
        }
        Node temp = this.head;
        for (int i = 0; i < index - 1 && temp != null; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        size--;
    }


    public static void main(String[] args) {
        MyLinkedList my = new MyLinkedList();
        my.addAtHead(1);
        my.addAtTail(3);
        my.addAtIndex(1,2);
        my.get(1);
        my.deleteAtIndex(1);
        my.get(1);
    }
}
